<?php

namespace App\Service\product;

use App\Models\order\OrderModel;
use App\Models\product\ProductModel;
use App\Models\users\UsersAmountRecordModel;
use App\Service\users\AccountRecordService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use lxs\config\BaseStatic;
use lxs\tools\DataHandle;

class ProductStatisticsService extends BaseStatic
{

    /**
     * 获取产品拉新统计数据
     * @param $uid int 用户id
     * @param $page int 页码
     * @param $pageSize int 每页数量
     * @param $is_show int 是否全部展示
     * @param $search_data array 搜索条件
     * @return array
     */
    public function getProductStatisticsData(int $uid, int $page, int $pageSize, int $is_show=1, array $search_data=[]): array
    {
        list($yesterday_start, $yesterday_end) = DataHandle::getTimeRange('yesterday');
        list($today_start, $today_end) = DataHandle::getTimeRange('today');

        $sql = "SELECT
                    p.product_title, ppr.popularize_name,
                    (SELECT COUNT(1) FROM oa_users_new_product_record AS l WHERE l.product_id = son.id) AS new_total,
                    (SELECT COUNT(1) FROM oa_order AS o WHERE o.product_id = son.id AND o.order_status in (1,2)) as new_order_total,
                    (SELECT COUNT(1) FROM oa_users_new_product_record AS l WHERE l.product_id = son.id AND l.create_time BETWEEN $today_start AND $today_end) as new_today_num,
                    (SELECT COUNT(1) FROM oa_order AS o WHERE o.product_id = son.id AND o.order_status in (1,2) AND o.pay_time BETWEEN $today_start AND $today_end) as new_today_order_num,
                    (SELECT COUNT(1) FROM oa_users_new_product_record AS l WHERE l.product_id = son.id AND l.create_time BETWEEN $yesterday_start AND $yesterday_end) as new_yesterday_num
                FROM oa_product_son AS son
                    LEFT JOIN oa_product AS p ON p.id = son.product_id
                    LEFT JOIN oa_product_popularize AS ppr ON ppr.id = son.popularize_id
                    WHERE son.id = any(SELECT product_id FROM oa_users_new_product_record WHERE uid = $uid)";

        if (isset($search_data['product_title'])) {
            $sql .= " AND p.product_title like '%{$search_data['product_title']}%'";
        }

        if (isset($search_data['data_time'])) {
            $data_time_start = strtotime($search_data['data_time'][0]);
            $data_time_end = strtotime($search_data['data_time'][1]);
            $sql .= " AND l.create_time BETWEEN $data_time_start AND $data_time_end";
        }

        $count = count(DB::select($sql));

        if ($is_show == 1) {
            $offset = $pageSize * ($page - 1);
            $sql .= " LIMIT $offset, $pageSize";
        } else {
            $sql .= " LIMIT 3";
        }

        $productList = DB::select($sql);
        foreach ($productList as $val) {
            $val->new_compare = $val->new_today_num - $val->new_yesterday_num;
            unset($val->new_yesterday_num);
        }

        return [
            'lists' => $productList,
            'page' => $page,
            'page_size' => $pageSize,
            'total' => $count
        ];
    }


    /**
     * 获取产品收益统计数据
     * @param $uid int 用户id
     * @param $page int 页码
     * @param $pageSize int 每页数量
     * @param $search_data array 搜索条件
     * @return array
     */
    public function getProductIncomeStatisticsData(int $uid, int $page, int $pageSize, array $search_data=[]): array
    {

        list($today_start, $today_end) = DataHandle::getTimeRange();
        list($yesterday_start, $yesterday_end) = DataHandle::getTimeRange('yesterday');
        list($month_start, $month_end) = DataHandle::getTimeRange('month');
        list($last_month_start, $last_month_end) = DataHandle::getTimeRange('last_month');

        // 今日成单数（笔）
        $statistics['today_buy_count'] = UsersAmountRecordModel::where('uid', $uid)
            ->where('deleted_at', 0)
            ->where('credit_type', AccountRecordService::USER_AMOUNT)
            ->where('type', AccountRecordService::TYPE_ORDER)
            ->where('num', '>', 0)
            ->where('create_time', '>=', $today_start)
            ->where('create_time', '<=', $today_end)
            ->count();
        // 昨天成单数（笔）
        $yesterday_buy_count = UsersAmountRecordModel::where('uid', $uid)
            ->where('deleted_at', 0)
            ->where('credit_type', AccountRecordService::USER_AMOUNT)
            ->where('type', AccountRecordService::TYPE_ORDER)
            ->where('num', '>', 0)
            ->where('create_time', '>=', $yesterday_start)
            ->where('create_time', '<=', $yesterday_end)
            ->count();
        // 今日成单数与昨天比较（笔）
        $statistics['today_buy_compare'] = $statistics['today_buy_count'] - $yesterday_buy_count;

        // 今日预估收益（元）
        $statistics['today_income_num'] = UsersAmountRecordModel::where('uid', $uid)
            ->where('deleted_at', 0)
            ->where('credit_type', AccountRecordService::USER_CREDIT)
            ->where('type', AccountRecordService::TYPE_ORDER)
            ->where('num', '>', 0)
            ->where('create_time', '>=', $today_start)
            ->where('create_time', '<=', $today_end)
            ->sum('num');
        // 昨天预估收益（元）
        $yesterday_income_num = UsersAmountRecordModel::where('uid', $uid)
            ->where('deleted_at', 0)
            ->where('credit_type', AccountRecordService::USER_CREDIT)
            ->where('type', AccountRecordService::TYPE_ORDER)
            ->where('num', '>', 0)
            ->where('create_time', '>=', $yesterday_start)
            ->where('create_time', '<=', $yesterday_end)
            ->sum('num');
        // 今日预估收益与昨天比较（元）
        $statistics['today_income_compare'] = $statistics['today_income_num'] - $yesterday_income_num;

        // 本月成单数（笔）
        $statistics['month_buy_count'] = UsersAmountRecordModel::where('uid', $uid)
            ->where('deleted_at', 0)
            ->where('credit_type', AccountRecordService::USER_AMOUNT)
            ->where('type', AccountRecordService::TYPE_ORDER)
            ->where('num', '>', 0)
            ->where('create_time', '>=', $month_start)
            ->where('create_time', '<=', $month_end)
            ->count();
        // 上月成单数（笔）
        $last_month_buy_count = UsersAmountRecordModel::where('uid', $uid)
            ->where('deleted_at', 0)
            ->where('credit_type', AccountRecordService::USER_AMOUNT)
            ->where('type', AccountRecordService::TYPE_ORDER)
            ->where('num', '>', 0)
            ->where('create_time', '>=', $last_month_start)
            ->where('create_time', '<=', $last_month_end)
            ->count();
        // 本月成单数与上月比较（笔）
        $statistics['month_buy_compare'] = $statistics['month_buy_count'] - $last_month_buy_count;

        // 本月预估收益（元）
        $statistics['month_income_num'] = UsersAmountRecordModel::where('uid', $uid)
            ->where('deleted_at', 0)
            ->where('credit_type', AccountRecordService::USER_CREDIT)
            ->where('type', AccountRecordService::TYPE_ORDER)
            ->where('num', '>', 0)
            ->where('create_time', '>=', $month_start)
            ->where('create_time', '<=', $month_end)
            ->sum('num');
        // 上月预估收益（元）
        $last_month_income_num = UsersAmountRecordModel::where('uid', $uid)
            ->where('deleted_at', 0)
            ->where('credit_type', AccountRecordService::USER_CREDIT)
            ->where('type', AccountRecordService::TYPE_ORDER)
            ->where('num', '>', 0)
            ->where('create_time', '>=', $last_month_start)
            ->where('create_time', '<=', $last_month_end)
            ->sum('num');
        // 本月预估收益与上月比较（元）
        $statistics['month_income_compare'] = $statistics['month_income_num'] - $last_month_income_num;

        $query = OrderModel::leftJoin('product_son', 'product_son.id', '=', 'order.product_id')
            ->leftJoin('product', 'product.id', '=', 'product_son.product_id')
            ->select('order.*', 'product.product_title', 'product.online_platform')
            ->where('order.uid', $uid)
            ->where('order.deleted_at', 0);

        if (isset($search_data['product_title']) && $search_data['product_title'] != '') {
            $query->where('product.product_title', 'like', '%' . $search_data['product_title'] . '%');
        }

        if (isset($search_data['data_time']) && $search_data['data_time'] != '') {
            $query->where(function ($query) use ($search_data) {
                $query->where('order.create_time', '>=', strtotime($search_data['data_time'][0]))
                    ->where('order.create_time', '<=', strtotime($search_data['data_time'][1]));
            });
        }

        $lists = $query->orderBy('order.create_time', 'desc')->paginate($pageSize, ['*'], 'page', $page);
        foreach ($lists as $key => $val) {
            $online_platform_name = ProductModel::getOnlinePlatform($val['online_platform']);
            $val['product_title'] = $val['product_title'] . '(' . $online_platform_name . ')';
            $lists[$key]['order_status_value'] = OrderModel::getOrderStatusValues($val['order_status']);
        }

        return [
            'statistics' =>$statistics,
            'lists' => $lists,
        ];
    }


}
